﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using School.Entities;
using School.Common;
using System.Collections;
using School.Service.BOOKS;
using System.Drawing;

namespace School.Pages.BOOKS
{
    public partial class SRV_BOOKS_ORDERPAY : System.Web.UI.Page
    {
        List<GrdObjectBook> gridLst;
        private SchoolEntities db = new SchoolEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if ((IQueryable<int>)Session["privilage"] != null)
            {
                var x = (IQueryable<int>)Session["privilage"];

                if (x.Contains(1105) == true)
                {
                    if (!this.Page.IsPostBack)
                    {

                        gridLst = new List<GrdObjectBook>();
                        hshow.Value = "0";
                    }
                    else
                    {

                        gridLst = (List<GrdObjectBook>)Session["gridLst"];

                    }
                    Fillddl();
                    lblResult.Text = "";
                }
                else
                    Response.Redirect("../organization/no_privelege.aspx");
            }
            else
                Response.Redirect("../organization/no_privelege.aspx");
        }
        private void Fillddl()
        {
            DropDownList ddl = ((DropDownList)(CampusPackage1.FindControl("ddlGrade")));
            ddl.AutoPostBack = true;
            ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);

            DropDownList ddlGrade = ((DropDownList)(CampusPackage2.FindControl("ddlGrade")));
            ddlGrade.AutoPostBack = true;
            ddlGrade.SelectedIndexChanged += new EventHandler(ddlGrade_SelectedIndexChanged);
        }

        void ddlGrade_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (CampusPackage2.CampusId != "0" && CampusPackage2.CertificateId != "0"
                && CampusPackage2.StageId != "0" && CampusPackage2.GradeId != "0")
            {
                ddlStudents.DataSource = School.Admission.Student.AllFullName(int.Parse(CampusPackage2.CampusId),
                    int.Parse(CampusPackage2.CertificateId), int.Parse(CampusPackage2.StageId), int.Parse(CampusPackage2.GradeId));
                ddlBind(ddlStudents);
            }
            else
            {
                lblResult.ForeColor = Color.Red;
                lblResult.Text = "يجب اختيار المجمع والشهاده والمرحله والصف اولا";
                
            }
        }

        void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList Gradeddl = (DropDownList)sender;
            if (Gradeddl.SelectedIndex != 0)
            {
                ddlBooks.DataSource = School.Service.BOOKS.SRV_BOOKS.AllBooks().Where(s => s.Campus_Id == long.Parse(CampusPackage1.CampusId))
                    .Where(s => s.Cer_Id == long.Parse(CampusPackage1.CertificateId)).Where(s => s.Stage_Id == long.Parse(CampusPackage1.StageId))
                    .Where(s => s.Grad_Id == long.Parse(CampusPackage1.GradeId));
                ddlBind(ddlBooks);
            }
        }

        private void ddlBind(DropDownList ddl)
        {
            ddl.Items.Clear();
            ddl.Items.Insert(0, new ListItem("اختيار", "0"));
            ddl.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (CampusPackage1.CampusId != "0" && CampusPackage1.CertificateId != "0" &&
                CampusPackage1.StageId!="0" && CampusPackage1.GradeId != "0" &&
                ddlBooks.SelectedValue != "0" && ddlBooks.SelectedValue != "0"
               && !string.IsNullOrEmpty(txtValue.Text) && ddlStudents.SelectedValue != "0")
            {
                // if (gridLst != null)
                int camId = int.Parse(CampusPackage1.CampusId);
                int cerId = int.Parse(CampusPackage1.CertificateId);
                int stageId = int.Parse(CampusPackage1.StageId);
                int GradeId = int.Parse(CampusPackage1.GradeId);
                int book_ID = int.Parse(ddlBooks.SelectedValue);
                if (db.SRV_Book.Where(s => s.Id == book_ID).FirstOrDefault().BookQty < long.Parse(txtValue.Text))
                {
                    lblResult.ForeColor = Color.Red;
                    lblResult.Text = "الكميه الموجوده بالمخزن لاتسمح بالصرف";
                    return;
                }
                if (gridLst == null)
                    gridLst = new List<GrdObjectBook>();
                foreach (GrdObjectBook item in gridLst)
                {
                    if (item.bookId == book_ID)
                    {
                        lblResult.ForeColor = Color.Red;
                        lblResult.Text = "هذا الكتاب قد تم ادخاله من فبل";
                        return;
                    }
                }
                gridLst.Add(new GrdObjectBook()
                {
                    CampusId = camId,
                    StudentId = int.Parse(ddlStudents.SelectedValue),
                    CampusName = db.ORG_Campus.Where(s => s.Id == camId).FirstOrDefault().Name,
                    CerId = cerId,
                    CerName = db.ORG_Certificate.Where(s => s.Id == cerId).FirstOrDefault().Name,
                    StageId = stageId,
                    StageName = db.ORG_Stage.Where(s => s.Id == stageId).FirstOrDefault().Name,
                    GradeId = GradeId,
                    GradeName = db.ORG_Grade.Where(s => s.Id == GradeId).FirstOrDefault().Name,
                    bookId = book_ID,
                    BookName = db.SRV_Book.Where(s => s.Id == book_ID).FirstOrDefault().Name,
                    UserQty = int.Parse(txtValue.Text),
                    PriceId = db.SRV_Book_Price.Where(s => s.Book_Id == book_ID).OrderByDescending(s => s.Price_Id).FirstOrDefault().Price_Id,
                    PriceName = db.SRV_Book_Price.Where(s => s.Book_Id == book_ID).OrderByDescending(s => s.Price_Id).FirstOrDefault().Price,
                    TotalPrice = int.Parse(txtValue.Text) * db.SRV_Book.Where(s => s.Id == book_ID).FirstOrDefault().SRV_Book_Price.FirstOrDefault().Price,
                    DiscountPercent = CalculateDiscount(db.SRV_Book.Where(s => s.Id == book_ID).FirstOrDefault().SRV_Book_Price.FirstOrDefault().Price),
                    PriceWzDiscount = GetPriceWzDiscount()
                });
                Session["gridLst"] = gridLst;
                gvData.DataSource = gridLst.ToList();
                gvData.DataBind();
                btnGetDiscounts.Enabled = false;

            }
        }
      
        private double GetPriceWzDiscount()
        {
            int bookID = int.Parse(ddlBooks.SelectedValue);
            double TotalPrice = int.Parse(txtValue.Text) * db.SRV_Book.Where(s => s.Id == bookID).FirstOrDefault().SRV_Book_Price.FirstOrDefault().Price;
            double TotalPercent = CalculateDiscount(TotalPrice);
            double PriceWzDiscount = TotalPrice - double.Parse(TotalPercent.ToString());
            if (PriceWzDiscount < 0)
                return 0;
            return PriceWzDiscount;
        }

        private double CalculateDiscount(double TotalPrice)
        {
           List<DiscountObject> lstdiscount = new List<DiscountObject>();
           double totalDiscountValue = 0;
           foreach (GridViewRow row in gvDiscountApplay.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    CheckBox chbxdiscount = (CheckBox)row.Cells[0].FindControl("ChkDiscount");
                    Label LblValue = (Label)row.Cells[3].FindControl("LblValue");
                    if (chbxdiscount.Checked)
                    {
                        long Id = long.Parse(gvDiscountApplay.DataKeys[row.RowIndex].Value.ToString());
                        lstdiscount.Add(new DiscountObject() {
                           Id = Id,
                           Name = db.ACC_Discount.Where(s=>s.Id == Id).FirstOrDefault().Name,
                           Type = db.ACC_Discount.Where(s=>s.Id == Id).FirstOrDefault().Type,
                           Value = Convert.ToDecimal(LblValue.Text)
                        });
                    }
                }
             }
           Session["lstDiscounts"] = lstdiscount;
           foreach (DiscountObject discount in lstdiscount)
           {
               if (discount.Type == 2)
               {
                   totalDiscountValue += ((TotalPrice * double.Parse(discount.Value.ToString())) / 100);
               }
               else if(discount.Type ==1)
                   totalDiscountValue += double.Parse(discount.Value.ToString());

           }
           return totalDiscountValue;
        }
      
        private IEnumerable<DiscountObject> GetDiscounts(int studentId)
        {
            int fatherjobId = 0, fatherStatusId = 0, MotherJobId = 0, MotherStatusId = 0;

            if (School.Common.StudentData.getfatherjob(studentId).FirstOrDefault() != null)
                fatherjobId = School.Common.StudentData.getfatherjob(studentId).FirstOrDefault().Id;

            if (School.Common.StudentData.getfatherStatus(studentId).FirstOrDefault() != null)
                fatherStatusId = School.Common.StudentData.getfatherStatus(studentId).FirstOrDefault().Id;

            if (School.Common.StudentData.getmotherjob(studentId).FirstOrDefault() != null)
                MotherJobId = School.Common.StudentData.getmotherjob(studentId).FirstOrDefault().Id;

            if (School.Common.StudentData.getmotherStatus(int.Parse(ddlStudents.SelectedValue)).FirstOrDefault() != null)
                MotherStatusId = School.Common.StudentData.getmotherStatus(studentId).FirstOrDefault().Id;

            IEnumerable<DiscountObject> lstDiscount = School.Common.Finance.GetDiscounts("400", long.Parse(CampusPackage1.CampusId), long.Parse(CampusPackage1.CertificateId),
                long.Parse(CampusPackage1.StageId), long.Parse(CampusPackage1.GradeId),
               fatherjobId, fatherStatusId, MotherJobId, MotherStatusId);

            return lstDiscount;

        }

        protected void btnpayment_Click(object sender, EventArgs e)
        {
            if (CampusPackage1.CampusId != "0" && CampusPackage1.CertificateId != "0" &&
                CampusPackage1.StageId != "0" && CampusPackage1.GradeId != "0" &&
                CampusPackage2.CampusId != "0" && CampusPackage2.CertificateId != "0" &&
                CampusPackage2.StageId != "0" && CampusPackage2.GradeId != "0" && ddlStudents.SelectedValue != "0")
            {
                gridLst = (List<GrdObjectBook>)Session["gridLst"];
                bool check = false;
                long paymentOrderNumber = School.Common.Structure.GetPayment_Order_Number();
                if (gridLst != null)
                {
                    if (gridLst.Count > 0)
                    {
                        List<DiscountObject> lstDiscounts = null;
                        Hashtable table = null;
                        bool checkresult = false;
                        long OrderId;
                        double totalPrice = 0;
                        foreach (GrdObjectBook item in gridLst)
                        {
                            totalPrice += item.PriceWzDiscount;
                        }
                        check = School.Service.BOOKS.SRV_Book_PaymentOrder.OrderPayInsert(new SRV_BOOK_Payment_Order()
                        {
                            Student_Id = long.Parse(ddlStudents.SelectedValue),
                            Value = Convert.ToDecimal(totalPrice.ToString()),
                            Payment_Order_Number = paymentOrderNumber,
                            Date = DateTime.Now
                        }, out OrderId);
                        foreach (GrdObjectBook item in gridLst)
                        {
                            checkresult = false;
                            table = new Hashtable();
                            if (check == true)
                            {
                                if (School.Service.BOOKS.SRV_Book_PaymentOrder.OrderPayItemsInsert(new SRV_BOOK_PAYMENT_ITEMS()
                                {
                                    Order_Id = OrderId,
                                    Book_Id = item.bookId,
                                    UnitPrice = db.SRV_Book_Price.OrderByDescending(s => s.Price_Id).Where(s => s.Book_Id == item.bookId).FirstOrDefault().Price,
                                    BookQty = item.UserQty,
                                    Payment_Order_Number = paymentOrderNumber
                                }))
                                {
                                    if (GetDiscounts(item.CampusId, item.CerId, item.StageId, item.GradeId, item.StudentId) != null)
                                        lstDiscounts = GetDiscounts(item.CampusId, item.CerId, item.StageId, item.GradeId, item.StudentId).ToList();
                                    if (lstDiscounts != null)
                                    {
                                        foreach (DiscountObject discount in lstDiscounts)
                                        {
                                            table.Add(discount.Id, OrderId);
                                        }
                                        if (School.Service.BOOKS.SRV_Book_PaymentOrder.OrderDiscountInsert(table))
                                        {
                                            //Session["lstDiscounts"] = lstDiscounts;
                                            checkresult = true;
                                        }
                                    }
                                }
                            }
                        }
                        int studentid = Convert.ToInt32(ddlStudents.SelectedValue);
                        int campusId = Convert.ToInt32(CampusPackage2.CampusId);
                        int cerId = Convert.ToInt32(CampusPackage2.CertificateId);
                        int GradeId = Convert.ToInt32(CampusPackage2.GradeId);
                        int StageId = Convert.ToInt32(CampusPackage2.StageId);
                        var nam = (from s in db.TE_Student where s.Id == studentid select s).FirstOrDefault();
                        var query = (from o in db.SRV_BOOK_Payment_Order where o.TE_Student.Id == nam.Id && o.Payment_Order_Number == paymentOrderNumber select new { sname = o.TE_Student.Ar_FirstName + " " + o.TE_Student.Ar_SecondName + " " + o.TE_Student.Ar_ThirdNmae + " " + o.TE_Student.Ar_FourthName, Payo = o.Payment_Order_Number });//, Date = DateTime.Now.ToString("dd/MM/yyyy") };
                        string CamName = db.ORG_Campus.Where(s => s.Id == campusId).FirstOrDefault().Name;
                        string CerName = db.ORG_Certificate.Where(s => s.Id == cerId).FirstOrDefault().Name;
                        string GradeName = db.ORG_Grade.Where(s => s.Id == GradeId).FirstOrDefault().Name;
                        string StageName = db.ORG_Stage.Where(s => s.Id == StageId).FirstOrDefault().Name;
                        string StudentName = nam.Ar_FirstName.ToString() + " " + nam.Ar_SecondName.ToString() + " " + nam.Ar_ThirdNmae.ToString() + " " + nam.Ar_FourthName.ToString();
                        studentDataReport stude = new studentDataReport();
                        stude.CamName = CamName;
                        stude.GradeName = GradeName;
                        stude.PayNum = paymentOrderNumber;
                        stude.Price = GetTotalPrice();
                        stude.StageName = StageName;
                        stude.StudentName = StudentName;
                        stude.CerName = CerName;
                        Session["stude"] = stude;
                        if (check)
                        {
                            hshow.Value = "1";
                            ReportViewer1.LocalReport.Refresh();
                            lblResult.ForeColor = Color.Green;
                            lblResult.Text = "تمت الاضافه بنجاح";
                        }
                        else
                        {
                            lblResult.ForeColor = Color.Red;
                            lblResult.Text = "حدث خطا فى ادخال البيانات";
                        }
                    }
                }
            }
            btnGetDiscounts.Enabled = true;
        }

        private void ClearData()
        {
            gridLst = (List<GrdObjectBook>)Session["gridLst"];
            gridLst.Clear();
            Session["gridLst"] = gridLst;
            gvData.DataSource = gridLst.ToList();
            gvData.DataBind();
        }

        private IEnumerable<DiscountObject> GetDiscounts(long CampID, long cerID, long StageID, long GradeID, int studentId)
        {
            int fatherjobId = 0, fatherStatusId = 0, MotherJobId = 0, MotherStatusId = 0;

            if (School.Common.StudentData.getfatherjob(studentId).FirstOrDefault() != null)
                fatherjobId = School.Common.StudentData.getfatherjob(studentId).FirstOrDefault().Id;

            if (School.Common.StudentData.getfatherStatus(studentId).FirstOrDefault() != null)
                fatherStatusId = School.Common.StudentData.getfatherStatus(studentId).FirstOrDefault().Id;

            if (School.Common.StudentData.getmotherjob(studentId).FirstOrDefault() != null)
                MotherJobId = School.Common.StudentData.getmotherjob(studentId).FirstOrDefault().Id;

            if (School.Common.StudentData.getmotherStatus(int.Parse(ddlStudents.SelectedValue)).FirstOrDefault() != null)
                MotherStatusId = School.Common.StudentData.getmotherStatus(studentId).FirstOrDefault().Id;

            return School.Common.Finance.GetDiscounts("400", CampID, cerID,
                StageID, GradeID, fatherjobId, fatherStatusId, MotherJobId, MotherStatusId);
        }

        protected void gvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            gridLst = (List<GrdObjectBook>)Session["gridLst"];
            if (gridLst != null)
            {
                GridViewRow selectedRow = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
                gridLst.RemoveAt(selectedRow.RowIndex);
                 gvData.DataSource = gridLst.ToList();
                gvData.DataBind();
                Session["gridLst"] = gridLst;
            }
        }

        protected void gvData_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

        }

        protected void ddlStudents_SelectedIndexChanged(object sender, EventArgs e)
        {
            gridLst = (List<GrdObjectBook>)Session["gridLst"];
            if (gridLst != null)
            {
                gridLst.Clear();
                gvData.DataSource = gridLst.ToList();
                gvData.DataBind();
            }
        }

        private List<GrdObjectBook> GetTotalPrice(string s)
        {
            List<GrdObjectBook> lstitems = new List<GrdObjectBook>();
            foreach (GridViewRow row in gvData.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    lstitems.Add(new GrdObjectBook()
                    {
                        BookName = row.Cells[4].Text,
                        PriceName = Convert.ToDouble(row.Cells[5].Text),
                        UserQty = Convert.ToInt32(row.Cells[6].Text),
                        TotalPrice = Convert.ToDouble(row.Cells[7].Text),
                        DiscountPercent = Convert.ToDouble(row.Cells[8].Text),
                        PriceWzDiscount = Convert.ToDouble(row.Cells[9].Text)
                    });
                }
            }
            return lstitems;
        }
    
        private string GetTotalPrice()
        {
            double totalPrice = 0;
            foreach (GridViewRow row in gvData.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    totalPrice += Convert.ToDouble(row.Cells[9].Text);
                }
            }
            return totalPrice.ToString();
        }

        protected void btnGetDiscounts_Click(object sender, EventArgs e)
        {
            if (CampusPackage1.CampusId != "0" && CampusPackage1.CertificateId != "0" &&
                CampusPackage1.StageId != "0" && CampusPackage1.GradeId != "0" &&
              ddlBooks.SelectedValue != "0"
              && !string.IsNullOrEmpty(txtValue.Text) && ddlStudents.SelectedValue != "0")
            {
                gvDiscountApplay.DataSource = GetDiscounts(int.Parse(ddlStudents.SelectedValue));
                gvDiscountApplay.DataBind();
            }
        }
        protected string GetType(object type)
        {
            return type.ToString() == "1" ? "مبلغ" : "نسبة";
        }

        protected string GetValue(object type, object value)
        {
            if (type.ToString() == "1")
                return value.ToString() ;
            else
                return value.ToString();
        }

        protected void OdsDiscount_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            if ((List<DiscountObject>)Session["lstDiscounts"] != null)
                e.InputParameters["DiscountLst"] = ((List<DiscountObject>)Session["lstDiscounts"]);
            else
                e.InputParameters["DiscountLst"] = new List<DiscountObject>();
          
        }

        protected void OdsGrdData_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            if ((List<GrdObjectBook>)Session["gridLst"] != null)
                e.InputParameters["GrdLst"] = ((List<GrdObjectBook>)Session["gridLst"]);
          
        }

        protected void OdsOrder_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            if ((studentDataReport)Session["stude"] != null)
            {
                studentDataReport stude = (studentDataReport)Session["stude"];
                e.InputParameters["stu_Name"] = stude.StudentName;
                e.InputParameters["CamName"] = stude.CamName;
                e.InputParameters["StageName"] = stude.StageName;
                e.InputParameters["CerName"] = stude.CerName;
                e.InputParameters["GradeName"] = stude.GradeName;
                e.InputParameters["PayNum"] = stude.PayNum;
                e.InputParameters["Price"] = GetTotalPrice();
            }
        }
    }
    public class studentDataReport
    {
        public string StudentName { get; set; }
        public string CamName { get; set; }
        public string StageName { get; set; }
        public string GradeName { get; set; }
        public string CerName { get; set; }
        public long PayNum { get; set; }
        public string Price { get; set; }

    }
}